package com.fhminyi.GUI;

import com.fhminyi.dao.OrderDao;
import com.fhminyi.dao.OrderItemDao;
import com.fhminyi.dao.ProductDao;
import com.fhminyi.dao.UserDao;
import com.fhminyi.model.Order;
import com.fhminyi.model.OrderItem;
import com.fhminyi.model.Product;
import com.fhminyi.model.User;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class ProductManagementFrame extends JFrame {
    private User currentUser;
    private ProductDao productDao = new ProductDao();
    private OrderDao orderDao = new OrderDao();
    private OrderItemDao orderItemDao = new OrderItemDao();
    private JPanel productPanel;
    private JTable orderTable;
    private DefaultTableModel orderTableModel;
    private JButton addButton;
    private JButton editButton;
    private JButton deleteButton;
    private JButton exportOrdersButton;
    private List<Product> products;

    public ProductManagementFrame(User user) {
        this.products = null;
        this.currentUser = user;
        setTitle("商品管理");
        setSize(1200, 800); // 调整窗口大小
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 设置边距
        mainPanel.setBackground(new Color(245, 245, 245)); // 设置背景色

        // 商品面板
        productPanel = new JPanel();
        productPanel.setLayout(new BoxLayout(productPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout，垂直排列
        productPanel.setBackground(new Color(245, 245, 245));

        JScrollPane productScrollPane = new JScrollPane(productPanel);
        productScrollPane.setBorder(BorderFactory.createTitledBorder("商品列表")); // 添加边框

        // 订单表格
        orderTableModel = new DefaultTableModel();
        orderTableModel.addColumn("订单ID");
        orderTableModel.addColumn("商品名称");
        orderTableModel.addColumn("商品数量");
        orderTableModel.addColumn("商品单价");
        orderTableModel.addColumn("订单总价");
        orderTableModel.addColumn("订单状态");
        orderTableModel.addColumn("订单日期");

        orderTable = new JTable(orderTableModel);
        orderTable.setFont(new Font("微软雅黑", Font.PLAIN, 14)); // 设置表格字体
        orderTable.setRowHeight(30); // 设置行高
        orderTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14)); // 设置表头字体
        orderTable.setSelectionBackground(new Color(0, 102, 204)); // 设置选中行背景色
        orderTable.setSelectionForeground(Color.WHITE); // 设置选中行文字颜色

        JScrollPane orderScrollPane = new JScrollPane(orderTable);
        orderScrollPane.setBorder(BorderFactory.createTitledBorder("订单列表")); // 添加边框

        // 使用 JSplitPane 分隔商品列表和订单列表
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, productScrollPane, orderScrollPane);
        splitPane.setResizeWeight(0.5); // 设置初始分隔比例为 50%
        splitPane.setDividerSize(5); // 设置分隔条大小
        splitPane.setOneTouchExpandable(true); // 允许一键展开/折叠

        mainPanel.add(splitPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        buttonPanel.setBackground(new Color(245, 245, 245));

        addButton = new JButton("添加商品");
        editButton = new JButton("编辑商品"); // 添加编辑商品按钮
        deleteButton = new JButton("删除商品");
        exportOrdersButton = new JButton("导出订单列表");

        // 设置按钮样式
        for (JButton button : new JButton[]{exportOrdersButton,addButton, editButton, deleteButton}) {
            button.setFont(new Font("微软雅黑", Font.BOLD, 14));
            button.setBackground(new Color(0, 102, 204)); // 设置按钮背景色
            button.setForeground(Color.WHITE); // 设置按钮文字颜色
            button.setFocusPainted(false); // 去除焦点边框
            button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20)); // 设置按钮内边距
        }

        addButton.addActionListener(e -> new AddProductFrame(currentUser).setVisible(true));

        editButton.addActionListener(e -> new EditProductFrame(currentUser, this.products).setVisible(true));

        deleteButton.addActionListener(e -> new DeleteProductFrame(currentUser).setVisible(true));

        exportOrdersButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportOrdersToCSV();
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(exportOrdersButton);
        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        loadProducts();
        loadOrders();

        add(mainPanel);
    }

    private void loadProducts() {
        productPanel.removeAll();
        try {
            List<Product> products = productDao.getProductsByUserId(currentUser.getUserId());
            this.products = products;
            for (Product product : products) {
                // 创建商品面板
                JPanel productItemPanel = new JPanel(new BorderLayout(10, 10));
                productItemPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1)); // 添加边框
                productItemPanel.setBackground(Color.WHITE); // 设置背景色
                productItemPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 200)); // 设置最大高度

                // 商品信息面板
                JPanel infoPanel = new JPanel(new GridLayout(6, 2, 5, 5));
                infoPanel.setBackground(Color.WHITE);

                JLabel nameLabel = new JLabel("商品名称: " + product.getProductName());
                JLabel categoryLabel = new JLabel("商品类别: " + product.getCategory());
                JLabel priceLabel = new JLabel("价格: " + product.getPrice());
                JLabel stockLabel = new JLabel("库存: " + product.getStock());
                JLabel sellerLabel = new JLabel("卖家用户名: " + getSellerUsername(product.getUserId()));
                JLabel descriptionLabel = new JLabel("描述: " + product.getDescription());

                infoPanel.add(nameLabel);
                infoPanel.add(categoryLabel);
                infoPanel.add(priceLabel);
                infoPanel.add(stockLabel);
                infoPanel.add(sellerLabel);
                infoPanel.add(descriptionLabel);

                // 图片面板
                JPanel imagePanel = new JPanel(new BorderLayout());
                imagePanel.setBackground(Color.WHITE);

                JLabel imageLabel = new JLabel();
                try {
                    ImageIcon icon = new ImageIcon(product.getImageLocation());
                    Image img = icon.getImage().getScaledInstance(150, 150, Image.SCALE_SMOOTH); // 调整图片大小
                    ImageIcon scaledIcon = new ImageIcon(img);
                    imageLabel.setIcon(scaledIcon);
                    imageLabel.setHorizontalAlignment(JLabel.CENTER); // 图片居中显示
                } catch (Exception e) {
                    imageLabel.setText("无法加载图片");
                }
                imagePanel.add(imageLabel, BorderLayout.CENTER);

                // 添加商品信息和图片面板到商品面板
                productItemPanel.add(infoPanel, BorderLayout.CENTER);
                productItemPanel.add(imagePanel, BorderLayout.EAST);

                productPanel.add(productItemPanel);
                productPanel.add(Box.createVerticalStrut(10)); // 添加垂直间距
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "获取商品列表失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
        productPanel.revalidate();
        productPanel.repaint();
    }

    private void loadOrders() {
        orderTableModel.setRowCount(0);
        try {
            List<Product> products = productDao.getProductsByUserId(currentUser.getUserId());
            for (Product product : products) {
                List<OrderItem> orderItems = orderItemDao.getOrderItemsByProductId(product.getProductId());
                for (OrderItem orderItem : orderItems) {
                    Order order = orderDao.getOrderById(orderItem.getOrderId());
                    orderTableModel.addRow(new Object[]{
                            order.getOrderId(),
                            product.getProductName(),
                            orderItem.getQuantity(),
                            orderItem.getPrice(),
                            order.getTotalPrice(),
                            order.getStatus(),
                            order.getOrderDate()
                    });
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "获取订单列表失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private String getSellerUsername(int userId) {
        UserDao userDao = new UserDao();
        User user = null;
        try {
            user = userDao.getUserById(userId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user.getUsername();
    }

    private void exportOrdersToCSV() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("导出订单列表");
        fileChooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
        fileChooser.setSelectedFile(new java.io.File("orders.csv"));

        int userSelection = fileChooser.showSaveDialog(this);
        if (userSelection == JFileChooser.APPROVE_OPTION) {
            java.io.File fileToSave = fileChooser.getSelectedFile();
            try (FileWriter writer = new FileWriter(fileToSave)) {
                // 写入CSV文件头
                writer.append("订单ID,商品名称,商品数量,商品单价,订单总价,订单状态,订单日期\n");

                // 获取订单列表
                List<Order> orders = orderDao.getAllOrders();
                for (Order order : orders) {
                    List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
                    for (OrderItem orderItem : orderItems) {
                        Product product = productDao.getProductById(orderItem.getProductId());
                        writer.append(Integer.toString(order.getOrderId()))
                                .append(",")
                                .append(product.getProductName())
                                .append(",")
                                .append(String.valueOf(orderItem.getQuantity()))
                                .append(",")
                                .append(String.valueOf(orderItem.getPrice()))
                                .append(",")
                                .append(String.valueOf(order.getTotalPrice()))
                                .append(",")
                                .append(order.getStatus())
                                .append(",")
                                .append(order.getOrderDate().toString())
                                .append("\n");
                    }
                }

                JOptionPane.showMessageDialog(this, "订单列表已成功导出到 " + fileToSave.getAbsolutePath(), "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException | SQLException ex) {
                JOptionPane.showMessageDialog(this, "导出订单列表失败", "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        }
    }

    // 测试
    public static void main(String[] args) {
        User user = new User();
        user.setUserId(1);
        new ProductManagementFrame(user).setVisible(true);
    }
}